import 'package:english_words/english_words.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:hive/hive.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:libflutter/DebugWidget.dart';
import 'package:libflutter/LanguageWidget.dart';
import 'package:libflutter/LifecycleWidget.dart';
import 'package:libflutter/language/MineLocalizations.dart';
import 'package:libflutter/language/MineLocalizationsDelegate.dart';

import 'package:flutter_boost/flutter_boost.dart';

/// 1 创建一个自定义的Binding，继承和with的关系如下，里面什么都不用写
class CustomFlutterBinding extends WidgetsFlutterBinding with BoostFlutterBinding {}

void main() async {
  ///这里的CustomFlutterBinding调用务必不可缺少，用于控制Boost状态的resume和pause
  CustomFlutterBinding();
  runApp(const MyApp());
}

class LocalNotification extends Notification {
  final Locale locale;

  LocalNotification(this.locale);
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<StatefulWidget> createState() {
    return MyAppState();
  }
}

class MyAppState extends State<MyApp> {
  Locale locale = const Locale('zh', 'CN');

  @override
  Widget build1(BuildContext context) {
    return NotificationListener(
      onNotification: (notification) {
        if (notification is LocalNotification) {
          setState(() {
            locale = notification.locale;
          });
        }
        return true;
      },
      child: MaterialApp(
        title: 'Flutter Demo',
        onGenerateTitle: (context) {
          // 此时context在Localizations的子树中
          return MineLocalizations.of(context).title;
        },
        theme: ThemeData(
          primarySwatch: Colors.blue,
        ),

        /// 控件中的语言的比如Material风格和基础风格的控件的多语言切换
        localizationsDelegates: const [
          // 本地化的代理类
          GlobalMaterialLocalizations.delegate,
          GlobalWidgetsLocalizations.delegate,
          // 注册我们的Delegate
          MineLocalizationsDelegate()
        ],

        /// 设置默认支持的语言
        supportedLocales: const [Locale('zh', 'CN'), Locale('en', 'US')],

        /// 语言变更的回掉
        localeResolutionCallback: (locale, supportedLocales) {
          print('MyApp >>localeResolutionCallback  >> $locale');
          print('MyApp >>localeResolutionCallback  >> $supportedLocales');
          return locale; // 默认返回
        },

        /// 语言变更的回掉
        // localeListResolutionCallback: (locales, supportedLocales) {
        //   print('MyApp >>localeListResolutionCallback  >> $locales');
        //   print('MyApp >>localeListResolutionCallback  >> $supportedLocales');
        //   return const Locale('en', 'US');
        // },
        // Locale Function(Locale locale, Iterable<Locale> supportedLocales)
        /// 设置出事的语言
        locale: locale,
        // 优先级localeResolutionCallback < localeListResolutionCallback[优先级最高]
        // 中文简体  const Locale('zh', 'CN')
        home: const DebugWidget(),
        // 默认的首页指定设置，如果不设置home 则在路由中使用 / 进行指定默认的主页
        routes: {
          "/": (context) {
            // 如果存在该路由，则使用 上边的home会出现问题报错
            return const Home(title: 'Flutter Demo Home Page');
          },
          "/homepage": (context) {
            return const MyHomePage(title: 'Flutter Demo Home Page');
          },
          "/lifecycle": (context) {
            return const LifecycleWidget();
          },
          "/language": (context) {
            return const LanguageWidget();
          },
          "/debug": (context) {
            return const DebugWidget();
          },
        },
      ),
    );
  }

  /// 由于很多同学说没有跳转动画，这里是因为之前exmaple里面用的是 [PageRouteBuilder]，
  /// 其实这里是可以自定义的，和Boost没太多关系，比如我想用类似iOS平台的动画，
  /// 那么只需要像下面这样写成 [CupertinoPageRoute] 即可
  /// (这里全写成[MaterialPageRoute]也行，这里只不过用[CupertinoPageRoute]举例子)
  ///
  /// 注意，如果需要push的时候，两个页面都需要动的话，
  /// （就是像iOS native那样，在push的时候，前面一个页面也会向左推一段距离）
  /// 那么前后两个页面都必须是遵循CupertinoRouteTransitionMixin的路由
  /// 简单来说，就两个页面都是CupertinoPageRoute就好
  /// 如果用MaterialPageRoute的话同理
  Route<dynamic>? routeFactory(RouteSettings settings, String? uniqueId) {
    print("routeFactory ${settings}  ${uniqueId}");
    return MaterialPageRoute(
        settings: settings,
        builder: (_) {
          switch (settings.name) {
            default:
              {
                return const DebugWidget();
              }
          }
        });
  }

  @override
  Widget build(BuildContext context) {
    return FlutterBoostApp(
      routeFactory,
      appBuilder: buildApp,
    );
  }

  @override
  Widget buildApp(Widget home) {
    return NotificationListener(
      onNotification: (notification) {
        if (notification is LocalNotification) {
          setState(() {
            locale = notification.locale;
          });
        }
        return true;
      },
      child: WillPopScope(
        onWillPop: () async {
          print(" WillPopScope  >>> ${Navigator.of(context).canPop()}");
          // if (Navigator.of(context).canPop()) {
          //   Navigator.of(context).pop();
          // } else {
          //   SystemNavigator.pop();
          // }
          return false;
        },
        child: MaterialApp(
          home: home,
          debugShowCheckedModeBanner: true,
          ///必须加上builder参数，否则showDialog等会出问题
          builder: (_, __) {
            return home;
          },
        ),
      ),
    );
  }
}

class Home extends StatelessWidget {
  const Home({super.key, required this.title});

  final String title;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Home App Bar"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(title),
            Text(
              title,
              style: Theme.of(context).textTheme.headlineMedium,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          print("asdasdadas");
        },
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  static State<MyHomePage> of(BuildContext context) {
    final State<MyHomePage>? result = context.findAncestorStateOfType<State<MyHomePage>>();
    if (result != null) {
      return result;
    }
    throw FlutterError.fromParts([context.describeElement('The context used was')]);
  }

  @override
  State<MyHomePage> createState() => SimpleTextState(text: "Simple View");
}

class SimpleTextState extends State<MyHomePage> {
  SimpleTextState({required this.text});

  final String text;

  @override
  Widget build(BuildContext context) {
    final wordPair = WordPair.random();
    return Center(
      child: Text(wordPair.toString()),
    );
  }
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headlineMedium,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ),
    );
  }
}
